import json
import uuid
from datetime import datetime


class Review:
    """
    评论类，代表用户对产品的评论
    """
    def __init__(self, review_id, product_id, customer_id, rating, comment, image_urls=None):
        self._review_id = review_id
        self._product_id = product_id
        self._customer_id = customer_id
        self._rating = rating  # 1-5分
        self._comment = comment
        self._image_urls = image_urls or []
        self._review_date = datetime.now()
        self._is_approved = True  # 默认审核通过
        self._likes = 0
        self._replies = []  # 回复列表
    
    def add_reply(self, reply):
        """添加回复"""
        self._replies.append(reply)
    
    def like(self):
        """点赞"""
        self._likes += 1
    
    def approve(self):
        """审核通过"""
        self._is_approved = True
    
    def disapprove(self):
        """审核不通过"""
        self._is_approved = False
    
    def to_dict(self):
        """将评论信息转换为字典"""
        return {
            'review_id': self._review_id,
            'product_id': self._product_id,
            'customer_id': self._customer_id,
            'rating': self._rating,
            'comment': self._comment,
            'image_urls': self._image_urls,
            'review_date': self._review_date.strftime('%Y-%m-%d %H:%M:%S'),
            'is_approved': self._is_approved,
            'likes': self._likes,
            'replies': [reply.to_dict() for reply in self._replies]
        }
    
    # Getter和Setter方法
    @property
    def review_id(self):
        return self._review_id
    
    @property
    def product_id(self):
        return self._product_id
    
    @property
    def customer_id(self):
        return self._customer_id
    
    @property
    def rating(self):
        return self._rating
    
    @rating.setter
    def rating(self, value):
        if 1 <= value <= 5:
            self._rating = value
    
    @property
    def comment(self):
        return self._comment
    
    @comment.setter
    def comment(self, value):
        self._comment = value
    
    @property
    def image_urls(self):
        return self._image_urls
    
    @image_urls.setter
    def image_urls(self, value):
        self._image_urls = value
    
    @property
    def review_date(self):
        return self._review_date
    
    @property
    def is_approved(self):
        return self._is_approved
    
    @property
    def likes(self):
        return self._likes
    
    @property
    def replies(self):
        return self._replies


class Reply:
    """
    回复类，代表对评论的回复
    """
    def __init__(self, reply_id, user_id, user_type, content):
        self._reply_id = reply_id
        self._user_id = user_id
        self._user_type = user_type  # "Customer" 或 "Seller" 或 "Admin"
        self._content = content
        self._reply_date = datetime.now()
    
    def to_dict(self):
        """将回复信息转换为字典"""
        return {
            'reply_id': self._reply_id,
            'user_id': self._user_id,
            'user_type': self._user_type,
            'content': self._content,
            'reply_date': self._reply_date.strftime('%Y-%m-%d %H:%M:%S')
        }
    
    # Getter方法
    @property
    def reply_id(self):
        return self._reply_id
    
    @property
    def user_id(self):
        return self._user_id
    
    @property
    def user_type(self):
        return self._user_type
    
    @property
    def content(self):
        return self._content
    
    @property
    def reply_date(self):
        return self._reply_date
    
    # Setter方法
    @content.setter
    def content(self, value):
        self._content = value


class ReviewManager:
    """
    评论管理器类，负责评论的创建、查找、更新等功能
    """
    def __init__(self, data_file="reviews.json", product_manager=None, user_manager=None):
        self._reviews = {}
        self._data_file = data_file
        self._product_manager = product_manager
        self._user_manager = user_manager
        self._load_reviews()
    
    def _load_reviews(self):
        """从文件加载评论数据"""
        try:
            with open(self._data_file, 'r', encoding='utf-8') as f:
                reviews_data = json.load(f)
                for review_data in reviews_data:
                    # 重建评论对象
                    review_id = review_data['review_id']
                    review = Review(
                        review_id=review_id,
                        product_id=review_data['product_id'],
                        customer_id=review_data['customer_id'],
                        rating=review_data['rating'],
                        comment=review_data['comment'],
                        image_urls=review_data.get('image_urls', [])
                    )
                    
                    # 恢复其他属性
                    review._likes = review_data.get('likes', 0)
                    review._is_approved = review_data.get('is_approved', True)
                    
                    # 恢复回复
                    for reply_data in review_data.get('replies', []):
                        reply = Reply(
                            reply_id=reply_data['reply_id'],
                            user_id=reply_data['user_id'],
                            user_type=reply_data['user_type'],
                            content=reply_data['content']
                        )
                        review.add_reply(reply)
                    
                    self._reviews[review_id] = review
        except FileNotFoundError:
            pass
        except json.JSONDecodeError:
            pass
        except Exception as e:
            print(f"加载评论数据时出错: {e}")
    
    def save_reviews(self):
        """保存评论数据到文件"""
        reviews_data = [review.to_dict() for review in self._reviews.values()]
        with open(self._data_file, 'w', encoding='utf-8') as f:
            json.dump(reviews_data, f, ensure_ascii=False, indent=2)
    
    def create_review(self, product_id, customer_id, rating, comment, image_urls=None):
        """创建新评论"""
        # 验证产品和用户是否存在
        if self._product_manager and not self._product_manager.get_product_by_id(product_id):
            return None, "产品不存在"
        
        if self._user_manager:
            customer = self._user_manager.get_user_by_id(customer_id)
            if not customer or customer.get_user_type() != "Customer":
                return None, "用户不存在或类型错误"
        
        # 验证评分范围
        if not 1 <= rating <= 5:
            return None, "评分必须在1-5之间"
        
        # 创建评论
        review_id = f"r{str(uuid.uuid4())[:8]}"
        review = Review(
            review_id=review_id,
            product_id=product_id,
            customer_id=customer_id,
            rating=rating,
            comment=comment,
            image_urls=image_urls
        )
        
        self._reviews[review_id] = review
        self.save_reviews()
        
        # 更新产品评分（如果有产品管理器）
        if self._product_manager:
            product = self._product_manager.get_product_by_id(product_id)
            if product and self._user_manager:
                seller = self._user_manager.get_user_by_id(product.seller_id)
                if seller and hasattr(seller, 'update_rating'):
                    seller.update_rating(rating)
                    self._user_manager.save_users()
        
        return review, "评论创建成功"
    
    def get_review_by_id(self, review_id):
        """通过ID查找评论"""
        return self._reviews.get(review_id)
    
    def get_reviews_by_product(self, product_id):
        """获取产品的所有评论"""
        return [review for review in self._reviews.values() 
                if review.product_id == product_id and review.is_approved]
    
    def get_reviews_by_customer(self, customer_id):
        """获取用户的所有评论"""
        return [review for review in self._reviews.values() 
                if review.customer_id == customer_id]
    
    def add_reply(self, review_id, user_id, user_type, content):
        """添加回复"""
        review = self.get_review_by_id(review_id)
        if not review:
            return False, "评论不存在"
        
        # 验证用户类型
        valid_types = ["Customer", "Seller", "Admin"]
        if user_type not in valid_types:
            return False, "用户类型错误"
        
        # 验证用户是否存在
        if self._user_manager and not self._user_manager.get_user_by_id(user_id):
            return False, "用户不存在"
        
        # 创建回复
        reply_id = f"rp{str(uuid.uuid4())[:8]}"
        reply = Reply(
            reply_id=reply_id,
            user_id=user_id,
            user_type=user_type,
            content=content
        )
        
        review.add_reply(reply)
        self.save_reviews()
        return True, "回复添加成功"
    
    def like_review(self, review_id):
        """点赞评论"""
        review = self.get_review_by_id(review_id)
        if review:
            review.like()
            self.save_reviews()
            return True
        return False
    
    def approve_review(self, review_id):
        """审核通过评论"""
        review = self.get_review_by_id(review_id)
        if review:
            review.approve()
            self.save_reviews()
            return True
        return False
    
    def disapprove_review(self, review_id):
        """审核不通过评论"""
        review = self.get_review_by_id(review_id)
        if review:
            review.disapprove()
            self.save_reviews()
            return True
        return False
    
    def get_product_average_rating(self, product_id):
        """获取产品的平均评分"""
        reviews = self.get_reviews_by_product(product_id)
        if not reviews:
            return 0.0
        
        total_rating = sum(review.rating for review in reviews)
        return round(total_rating / len(reviews), 1)
    
    def get_all_reviews(self):
        """获取所有评论（包括未审核的）"""
        return list(self._reviews.values())
    
    def delete_review(self, review_id):
        """删除评论"""
        if review_id in self._reviews:
            del self._reviews[review_id]
            self.save_reviews()
            return True
        return False